<template>
  <view class="repair-management-page">
    <!-- 顶部统计 -->
    <view class="stats-section">
      <view class="stats-card">
        <view class="stats-item" @click="viewOrdersByStatus(1)">
          <text class="stats-number">{{ statistics.pendingCount }}</text>
          <text class="stats-label">待处理</text>
        </view>
        <view class="stats-item" @click="viewOrdersByStatus(2)">
          <text class="stats-number">{{ statistics.inProgressCount }}</text>
          <text class="stats-label">进行中</text>
        </view>
        <view class="stats-item" @click="viewOrdersByStatus(4)">
          <text class="stats-number">{{ statistics.completedCount }}</text>
          <text class="stats-label">已完成</text>
        </view>
        <view class="stats-item" @click="viewUrgentOrders">
          <text class="stats-number">{{ statistics.urgentCount }}</text>
          <text class="stats-label">紧急工单</text>
        </view>
      </view>
    </view>

    <!-- 功能按钮 -->
    <view class="function-section">
      <view class="function-grid">
        <view class="function-item" @click="viewPendingOrders">
          <view class="function-icon" style="background: #ff4757">
            <u-icon name="clipboard" color="#fff" size="18"></u-icon>
          </view>
          <text class="function-text">待分配工单</text>
        </view>
        <view class="function-item" @click="viewMyOrders">
          <view class="function-icon" style="background: #2ed573">
            <u-icon name="account-check" color="#fff" size="18"></u-icon>
          </view>
          <text class="function-text">我的工单</text>
        </view>
      </view>
    </view>

    <!-- 工单列表 -->
    <view class="order-section">
      <view class="section-header">
        <text class="section-title">维修工单</text>
        <view class="filter-buttons">
          <u-button 
            type="primary" 
            size="small" 
            text="筛选" 
            plain 
            @click="showFilter = true"
          ></u-button>
        </view>
      </view>
      
      <view class="order-list">
        <view 
          v-for="order in orderList" 
          :key="order.id" 
          class="order-item"
          @click="viewOrderDetail(order)"
        >
          <view class="order-header">
            <text class="order-no">{{ order.orderNo }}</text>
            <u-tag 
              :text="order.statusName" 
              :type="getStatusType(order.status)" 
              size="mini"
            ></u-tag>
          </view>
          <view class="order-content">
            <text class="order-title">{{ order.title }}</text>
            <text class="order-address">{{ order.repairAddress }}</text>
            <view class="order-meta">
              <text class="order-time">{{ formatTime(order.createTime) }}</text>
              <text class="order-priority" :style="{ color: getPriorityColor(order.urgencyLevel) }">
                {{ order.urgencyLevelName }}
              </text>
            </view>
          </view>
          <view class="order-actions" v-if="order.canAccept || order.canAssign || order.canComplete">
            <u-button 
              v-if="order.canAccept" 
              type="warning" 
              size="mini" 
              text="受理" 
              @click.stop="acceptOrder(order)"
            ></u-button>
            <u-button 
              v-if="order.canAssign" 
              type="primary" 
              size="mini" 
              text="分配" 
              @click.stop="assignOrder(order)"
            ></u-button>
            <u-button 
              v-if="order.canComplete" 
              type="success" 
              size="mini" 
              text="完成" 
              @click.stop="completeOrder(order)"
            ></u-button>
          </view>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view class="load-more" v-if="hasMore">
        <u-button 
          type="primary" 
          size="small" 
          text="加载更多" 
          plain 
          @click="loadMore"
          :loading="loading"
        ></u-button>
      </view>
    </view>

    <!-- 筛选弹窗 -->
    <u-popup v-model:show="showFilter" mode="bottom" border-radius="10">
      <view class="filter-popup">
        <view class="popup-header">
          <text class="popup-title">筛选条件</text>
          <u-button type="primary" size="small" text="确定" @click="applyFilter"></u-button>
        </view>
        <view class="filter-content">
          <view class="filter-item">
            <text class="filter-label">工单状态</text>
            <u-radio-group v-model="filterForm.status" direction="horizontal">
              <u-radio label="全部" :name="null"></u-radio>
              <u-radio label="待处理" :name="1"></u-radio>
              <u-radio label="进行中" :name="2"></u-radio>
              <u-radio label="已完成" :name="4"></u-radio>
            </u-radio-group>
          </view>
          <view class="filter-item">
            <text class="filter-label">紧急程度</text>
            <u-radio-group v-model="filterForm.urgencyLevel" direction="horizontal">
              <u-radio label="全部" :name="null"></u-radio>
              <u-radio label="一般" :name="1"></u-radio>
              <u-radio label="紧急" :name="2"></u-radio>
              <u-radio label="非常紧急" :name="3"></u-radio>
            </u-radio-group>
          </view>
        </view>
      </view>
    </u-popup>

    <!-- 分配工单弹窗 -->
    <u-popup v-model:show="showAssignModal" mode="center" border-radius="10">
      <view class="assign-modal">
        <view class="modal-header">
          <text class="modal-title">分配维修工单</text>
        </view>
        <view class="modal-content">
          <view class="form-item">
            <text class="form-label">选择维修人员</text>
            <u-picker 
              v-model:show="showRepairmanPicker"
              :columns="repairmanColumns"
              @confirm="onRepairmanConfirm"
            >
              <view class="picker-input" @click="showRepairmanPicker = true">
                <text>{{ selectedRepairman ? selectedRepairman.name : '请选择维修人员' }}</text>
                <u-icon name="arrow-right" size="14"></u-icon>
              </view>
            </u-picker>
          </view>
          <view class="form-item">
            <text class="form-label">预计完成时间</text>
            <u-datetime-picker 
              v-model:show="showTimePicker"
              v-model="estimatedTime"
              @confirm="onTimeConfirm"
            >
              <view class="picker-input" @click="showTimePicker = true">
                <text>{{ estimatedTime || '请选择预计完成时间' }}</text>
                <u-icon name="arrow-right" size="14"></u-icon>
              </view>
            </u-datetime-picker>
          </view>
          <view class="form-item">
            <text class="form-label">备注说明</text>
            <u-textarea v-model="assignRemark" placeholder="请输入备注说明"></u-textarea>
          </view>
        </view>
        <view class="modal-actions">
          <u-button type="info" text="取消" @click="cancelAssign"></u-button>
          <u-button type="primary" text="确定分配" @click="confirmAssign"></u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { ref, onMounted } from 'vue'
import { repairWorkApi } from '@/api/repair-work'

export default {
  name: 'RepairManagement',
  setup() {
    // 响应式数据
    const loading = ref(false)
    const hasMore = ref(true)
    const showFilter = ref(false)
    const showAssignModal = ref(false)
    const showRepairmanPicker = ref(false)
    const showTimePicker = ref(false)
    
    // 统计数据
    const statistics = ref({
      pendingCount: 0,
      inProgressCount: 0,
      completedCount: 0,
      urgentCount: 0
    })
    
    // 工单列表
    const orderList = ref([])
    
    // 筛选条件
    const filterForm = ref({
      status: null,
      urgencyLevel: null
    })
    
    // 分配相关数据
    const currentAssignOrder = ref(null)
    const selectedRepairman = ref(null)
    const estimatedTime = ref('')
    const assignRemark = ref('')
    
    // 维修人员列表
    const repairmanColumns = ref([
      [
        { text: '张三', value: 1 },
        { text: '李四', value: 2 },
        { text: '王五', value: 3 }
      ]
    ])

    // 方法
    const viewOrdersByStatus = (status) => {
      filterForm.value.status = status
      applyFilter()
    }

    const viewUrgentOrders = () => {
      filterForm.value.urgencyLevel = 3
      applyFilter()
    }

    // 数据加载方法
    const loadStatistics = async () => {
      try {
        const response = await repairWorkApi.getMobileStatistics()
        if (response.code === 200 && response.data) {
          statistics.value = response.data
          console.log('统计数据加载成功:', response.data)
        }
      } catch (error) {
        console.error('加载统计数据失败:', error)
        uni.showToast({ 
          title: error.message || '加载统计数据失败', 
          icon: 'none' 
        })
      }
    }

    const loadOrderList = async () => {
      try {
        loading.value = true
        const response = await repairWorkApi.getMobilePendingAssignmentOrders(1, 20)
        if (response.code === 200 && response.data) {
          // 处理工单列表，添加操作权限字段
          const orders = (response.data.records || []).map(order => ({
            ...order,
            canAccept: order.status === 1, // 待受理状态可以受理
            canAssign: order.status === 2, // 已受理状态可以分配
            canComplete: order.status === 3 // 维修中状态可以完成
          }))
          orderList.value = orders
          hasMore.value = response.data.current < response.data.pages
          console.log('工单列表加载成功:', response.data)
        }
      } catch (error) {
        console.error('加载工单列表失败:', error)
        uni.showToast({ 
          title: error.message || '加载工单列表失败', 
          icon: 'none' 
        })
      } finally {
        loading.value = false
      }
    }

    const viewPendingOrders = () => {
      // 跳转到待分配工单页面
      uni.navigateTo({
        url: '/pages/property-work/repair-pending-assignment'
      })
    }

    const viewMyOrders = () => {
      // 跳转到我的工单页面
      uni.navigateTo({
        url: '/pages/property-work/repair-my-orders'
      })
    }


    const viewOrderDetail = (order) => {
      // TODO: 跳转到工单详情页面
      uni.navigateTo({
        url: `/pages/property-work/repair-detail?id=${order.id}`
      })
    }

    const acceptOrder = (order) => {
      console.log('受理工单，工单信息:', order)
      console.log('工单ID字段:', order.id, '类型:', typeof order.id)
      
      // 获取工单ID，尝试不同的可能字段名
      const orderId = order.id || order.orderId || order.repairOrderId
      
      if (!orderId) {
        console.error('工单ID不存在，工单对象:', order)
        uni.showToast({ 
          title: '工单ID不存在，无法受理', 
          icon: 'none' 
        })
        return
      }
      
      console.log('跳转到受理页面，工单ID:', orderId, '类型:', typeof orderId)
      
      // 确保ID是字符串类型
      const idStr = String(orderId)
      const url = `/pages/property-work/repair-accept?id=${idStr}`
      console.log('跳转URL:', url)
      
      // 跳转到受理页面
      uni.navigateTo({
        url: url
      })
    }

    const assignOrder = (order) => {
      currentAssignOrder.value = order
      showAssignModal.value = true
    }

    const completeOrder = (order) => {
      uni.showModal({
        title: '确认完成',
        content: '确认完成此维修工单吗？',
        success: (res) => {
          if (res.confirm) {
            // TODO: 调用完成工单接口
            uni.showToast({ title: '工单已完成', icon: 'success' })
          }
        }
      })
    }

    const applyFilter = () => {
      // TODO: 根据筛选条件重新加载数据
      showFilter.value = false
      uni.showToast({ title: '筛选条件已应用', icon: 'none' })
    }

    const loadMore = () => {
      loading.value = true
      // TODO: 加载更多数据
      setTimeout(() => {
        loading.value = false
        hasMore.value = false
      }, 1000)
    }

    const onRepairmanConfirm = (e) => {
      selectedRepairman.value = {
        id: e.value[0],
        name: e.text[0]
      }
    }

    const onTimeConfirm = (e) => {
      estimatedTime.value = e.value
    }

    const cancelAssign = () => {
      showAssignModal.value = false
      currentAssignOrder.value = null
      selectedRepairman.value = null
      estimatedTime.value = ''
      assignRemark.value = ''
    }

    const confirmAssign = () => {
      if (!selectedRepairman.value) {
        uni.showToast({ title: '请选择维修人员', icon: 'none' })
        return
      }
      
      // TODO: 调用分配工单接口
      uni.showToast({ title: '工单已分配', icon: 'success' })
      showAssignModal.value = false
    }

    const getStatusType = (status) => {
      const typeMap = {
        1: 'error',    // 待处理
        2: 'warning',  // 进行中
        3: 'info',     // 维修中
        4: 'success',  // 已完成
        5: 'info'      // 已取消
      }
      return typeMap[status] || 'info'
    }

    const getPriorityColor = (urgencyLevel) => {
      const colorMap = {
        1: '#999999',  // 一般
        2: '#ff9500',  // 紧急
        3: '#ff4757'   // 非常紧急
      }
      return colorMap[urgencyLevel] || '#999999'
    }

    const formatTime = (time) => {
      return new Date(time).toLocaleString('zh-CN')
    }

    // 生命周期
    onMounted(() => {
      // 加载统计数据和工单列表
      loadStatistics()
      loadOrderList()
    })

    return {
      loading,
      hasMore,
      showFilter,
      showAssignModal,
      showRepairmanPicker,
      showTimePicker,
      statistics,
      orderList,
      filterForm,
      currentAssignOrder,
      selectedRepairman,
      estimatedTime,
      assignRemark,
      repairmanColumns,
      viewOrdersByStatus,
      viewUrgentOrders,
      viewPendingOrders,
      viewMyOrders,
      viewOrderDetail,
      acceptOrder,
      assignOrder,
      completeOrder,
      applyFilter,
      loadMore,
      onRepairmanConfirm,
      onTimeConfirm,
      cancelAssign,
      confirmAssign,
      getStatusType,
      getPriorityColor,
      formatTime,
      loadStatistics,
      loadOrderList
    }
  },
  
  // 页面生命周期
  onShow() {
    // 页面显示时刷新数据
    this.loadStatistics()
    this.loadOrderList()
  }
}
</script>

<style lang="scss" scoped>
.repair-management-page {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.stats-section {
  margin-bottom: 20rpx;
}

.stats-card {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

.stats-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stats-number {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.stats-label {
  font-size: 24rpx;
  color: #666;
}

.function-section {
  margin-bottom: 20rpx;
}

.function-grid {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

.function-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.function-icon {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10rpx;
}

.function-text {
  font-size: 24rpx;
  color: #333;
  text-align: center;
}

.order-section {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.order-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.order-item {
  background: #f8f9fa;
  border-radius: 12rpx;
  padding: 20rpx;
  border-left: 6rpx solid #007bff;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.order-no {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.order-content {
  margin-bottom: 15rpx;
}

.order-title {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 8rpx;
  display: block;
}

.order-address {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 8rpx;
  display: block;
}

.order-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-time {
  font-size: 24rpx;
  color: #999;
}

.order-priority {
  font-size: 24rpx;
  font-weight: bold;
}

.order-actions {
  display: flex;
  gap: 10rpx;
  justify-content: flex-end;
}

.load-more {
  text-align: center;
  margin-top: 30rpx;
}

/* 弹窗样式 */
.filter-popup {
  background: white;
  padding: 30rpx;
  border-radius: 20rpx 20rpx 0 0;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.filter-content {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.filter-label {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.assign-modal {
  background: white;
  border-radius: 16rpx;
  width: 600rpx;
  padding: 30rpx;
}

.modal-header {
  text-align: center;
  margin-bottom: 30rpx;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.modal-content {
  display: flex;
  flex-direction: column;
  gap: 25rpx;
  margin-bottom: 30rpx;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.picker-input {
  background: #f8f9fa;
  border-radius: 8rpx;
  padding: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border: 2rpx solid #e9ecef;
}

.modal-actions {
  display: flex;
  gap: 20rpx;
  justify-content: center;
}
</style>
